import sys
import ToE.find_new_traffic as fnt
import ToE.max_min_fairness as mmf
import TE.threshold_TE as tt
import numpy as np
import pandas as pd

import read_func as rf


def ToE_TE(traffic_seq, pod_num, a_link_bandwidth, link_num):
    bandwidth_upper_bound = a_link_bandwidth * link_num
    new_traffic, S, virtual_r_array = fnt.get_new_traffic(traffic_seq, True, bandwidth_upper_bound)
    topo = mmf.Topology()
    topo = topo.topology([new_traffic], pod_num, a_link_bandwidth, link_num)
    
    shape = topo.shape
    capacity = np.array(topo)
    print('topo:')
    print(capacity)
    capacity = capacity.reshape(1, shape[0] * shape[1])
    pd.DataFrame(capacity).to_csv(f'./config/{pod_num}pod_topo.csv', header = False, index = False)

    ret = tt.Routing(topo)
    threshold = ret.routing(S, virtual_r_array, a_link_bandwidth)
    
    return threshold, virtual_r_array


def create_threshold_file(traffic_arr, pod_num, a_link_bandwidth, link_num, which_row, traffic_num):
    traffic_seq = traffic_arr[which_row : which_row + traffic_num]
    threshold, virtual_r_array = ToE_TE(traffic_seq, pod_num, a_link_bandwidth, link_num)
    threshold = threshold.reshape(1, pod_num * pod_num).astype(int)
    
    res_virtual_r = pd.DataFrame(virtual_r_array.reshape(1, pod_num))
    print('virtual_r:')
    print(res_virtual_r)
    res_virtual_r.to_csv(f'./config/{pod_num}pod_virtual_r.csv', header = False, index = False)

    res_threshold = pd.DataFrame(threshold)
    print('threshold:')
    print(res_threshold)
    res_threshold.to_csv(f'./config/{pod_num}pod_threshold.csv', header = False, index = False)


if __name__ == "__main__":
    pod_num = 4
    a_link_bandwidth = 100
    link_num = 20
    which_row = 0    # 哪一行流量开始作ToE和TE
    traffic_num = 5  # 用traffic_num行流量来做ToE和TE

    traffic_file = './traffic/' + str(pod_num) + 'pod_traffic.csv'
    traffic_arr = rf.get_traffic(traffic_file)
    create_threshold_file(traffic_arr, pod_num, a_link_bandwidth, link_num, which_row, traffic_num)
